import pdfplumber
import pandas as pd
import xlwt
import sys
import os,shutil
from django.http import FileResponse
from django.utils.encoding import escape_uri_path
from rest_framework.views import APIView
from rest_framework.response import Response
from utils.utils import toMd5,saveFile
from django.core.signals import request_finished
from apps.translate.signal import deleteSrcData
from apps.translate.config import pdftoexcel_base_path

class PdfToExcelAPIView(APIView):
    def post(self, request):
        data = saveFile(self, request, savepath=pdftoexcel_base_path)
        datas=[]
        try:
            for i in data:
                pdf_path = os.path.join(pdftoexcel_base_path, i+'.pdf')
                new_excel = pdftoexcel_base_path+i+'.%s'%'xlsx'
                # 获取该PDF总页数
                writer = pd.ExcelWriter(new_excel)
                with pdfplumber.open(pdf_path) as pdf:
                    for k in range(len(pdf.pages)):
                        table_obj = pdf.pages[k]
                        table_data = table_obj.extract_tables()
                        for t in table_data:
                            # 得到的table是嵌套list类型，转化成DataFrame
                            df = pd.DataFrame(t[1:], columns=t[0])
                            df.to_excel(writer, 'sheet%s'%k, header=True, index=False)
                            # 保存
                    writer.save()  
                datas.append(i)
        except Exception as e:
            return Response({'code': 4000, 'msg': e.args})   
        return Response({'code': 2000, 'msg': '转换完成', 'data': datas})
    
class GetPdfToExcelAPIView(APIView):
    def post(self,request):
         # 移动转行后的文件夹,如果是多个文件，则返回zip，一个的话直接返回xx.pdf
        if len(request.data)>1:
            secret_dir = toMd5(str(time.time()))
            path = pdftoexcel_base_path+"%s"%secret_dir
            os.makedirs(path)
            try:
                for i in request.data:
                     shutil.move(pdftoexcel_base_path+str(i)+'%s'%'.xlsx', path)
                     shutil.move(pdftoexcel_base_path+str(i)+'%s'%'.pdf', path)
                file_news = secret_dir +'.zip'
                z = zipfile.ZipFile(file_news, 'w', zipfile.ZIP_DEFLATED)
                for dirpath, dirnames, filenames in os.walk(path):
                    fpath = path
                    fpath = fpath and fpath + os.sep or ''
                    for filename in filenames:
                        z.write(os.path.join(dirpath, filename), fpath + filename)
                z.close()
                response = FileResponse(open(path+'/%s' %file_news, 'rb'))         
                response['Content-Type'] = "application/zip"        
                response['Content-Disposition'] = 'attachment;filename="%s"' % file_news 
                request_finished.send(sender='pdftoexcels',md5Items=[secret_dir])   
                return response
            except Exception as e:
                return Response({'code': 4001, 'msg': e.args})
        else:
            try:
                file_news = request.data[0]
                file_name = file_news+'.xlsx'
                response = FileResponse(open(pdftoexcel_base_path+'%s'%file_name, "rb"))
                response["Content-Type"] = "application/octet-stream"
                response["Content-Disposition"] = "attachment; filename*={}".format(escape_uri_path(file_name))
                request_finished.send(sender='pdftoexcel',md5Items=[file_news])   
            except Exception:
                return Response({'code': 4001, 'msg': e.args})
            return response
 

